var express = require('express');
// var fetch = require('node-fetch');
var router = express.Router();
const admService = require("../service/admService");
const { sha256, secretKey } = require('../utils/token');
const jwt = require("jsonwebtoken");
// const APP_ID = 'wxb8268348657f31e1';
// const SECRET = '9e2f4fe408676e8e08e4c0d56f896a9c';
const { v4: uuidv4 } = require('uuid');
const https = require('https');
// const httpsAgent = new https.Agent({ rejectUnauthorized: false });
// const { base64_decode } = require('../utils/token');
/* GET users listing. */
// router.get('/', function (req, res, next) {
//   res.send('respond with a resource');
// });

/**
 * @swagger
 * /admins/login:
 *    post:
 *      tags:
 *      - admins
 *      summary: 管理员登录
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                username:
 *                  type: string
 *                pwd:
 *                  type: string
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//登录
router.post('/login', async function (req, res, next) {
    let { username, pwd } = req.body;
    let data = await admService.login({ username, pwd: sha256(pwd) });
    // let data = await admService.login({ username, pwd });
    console.log("管理员", data);
    if (data.length > 0) {
        let token = jwt.sign({ data: data[0] }, secretKey);
        res.send({
            token,
            state: 1,
            str: "登陆成功"
        });
    } else {
        res.send({
            str: "登陆失败"
        });
    }
});


/**
 * @swagger
 * /admins/add:
 *    post:
 *      tags:
 *      - admins
 *      summary: 管理员注册
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                username:
 *                  type: string
 *                pwd:
 *                  type: string
 *                gender:
 *                  type: string
 *                headImg:
 *                  type: string
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//添加用户
router.post('/add', async function (req, res, next) {
    let { username, pwd, headImg, gender } = req.body;
    if (username == "" || pwd == "") {
        res.send({ data: "账号或密码不能为空" });
        return
    }
    let data = await admService.insert({ username, pwd: sha256(pwd), headImg, gender });
    // let data = await admService.insert({ username, pwd  });
    res.send({ data });
});

// //微信小程序登录注册
// router.get('/weixinLogin', async function (req, res) {
//     console.log("请求123131", req.query);
//     let code = req.query.code;
//     let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
//     console.log("url", url);
//     try {
//         let fetchResult = await fetch(url, {
//             agent: httpsAgent
//         });
//         let data = await fetchResult.json();
//         console.log('data', url, data)
//         if (!data.errcode) {
//             let user = await admService.userFind(data.openid);
//             if (Object.keys(user).length > 0) {
//                 res.send(user);
//             } else {
//                 let newUser = await admService.insert({ username: data.openid, pwd: '' });
//                 res.send(newUser);
//             }
//         } else {
//             res.send({});
//         }
//     } catch (e) {
//         console.log("error:", e);
//         res.send({});
//     }

// });

// //微信小程序用户上传的信息
// router.post('/weixinDetail:id', async function (req, res) {
//     let id = req.params.id;
//     let { nickname, image } = req.body;
//     let user = await admService.findById(id);
//     if (image) {
//         let strUUID = uuidv4();
//         base64_decode(image, "./public/image/" + strUUID + ".jpeg");
//         user.headImg = strUUID + ".jpeg";
//     };
//     if (nickname) {
//         console.log(nickname);
//         user.nickname = nickname
//     }
//     await admService.upData(id, user);
//     res.send(user);
// })


/**
 * @swagger
 * /admins/{id}:
 *    delete:
 *      tags:
 *      - admins
 *      summary: 删除管理员
 *      parameters:
 *      - name: id
 *        in: path
 *        description: 删除管理员id
 *        required: true
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//删除用户信息
router.delete('/:id', async function (req, res) {
    let { id } = req.params;
    let data = await admService.remove({ _id: id });
    res.send({ data });
});

/**
 * @swagger
 * /admins/{id}:
 *    put:
 *      tags:
 *      - admins
 *      summary: 修改管理员信息
 *      parameters:
 *      - name: id
 *        in: path
 *        description: 修改管理员id
 *        required: true
 *      requestBody:
 *        required: true
 *        content:
 *          application/x-www-form-urlencoded:
 *            schema:
 *              type: object
 *              properties:
 *                username:
 *                  type: string
 *                pwd:
 *                  type: string
 *                headImg:
 *                  type: string
 *                gender:
 *                  type: string
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//修改用户信息
router.put('/:id', async function (req, res) {
    let { id } = req.params;
    let { username, pwd, phone, email, privilege, headImg, gender } = req.body;
    if (pwd.length > 30) {
        pwd = pwd
    } else {
        pwd = sha256(pwd);
    }
    let data = await admService.upData(id, { username, pwd, phone, email, privilege, headImg, gender });
    res.send({ data });
});

//搜索用户信息
router.get('/', async function (req, res) {
    let { type, value, current, pageSize } = req.query;
    let searchObj = {};
    if (type) {
        if (type == "phone") {
            searchObj[type] = value;
        } else {
            searchObj[type] = { $regex: value };
        }
    };
    let data = await admService.search(searchObj, { current: current || 1, pageSize: pageSize || 10 });
    res.send({ data });
});

//查询用户是否存在
router.post("/username", async function (req, res, next) {
    let { username } = req.body;
    let data = await admService.userFind(username);
    if (data.length > 0) {
        res.send({
            state: 1,
            str: "已注册"
        })
    } else {
        res.send({
            state: 0,
            str: "未注册"
        })
    }
})

// 通过id查找
router.get('/:id', async function (req, res) {
    let { id } = req.params;
    let data = await admService.findById(id);
    res.send({ data });
});

module.exports = router;
